package com.itany.shop.filter;

import com.itany.shop.entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 石小俊
 */
//@WebFilter("/*")
public class CheckLoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 某些请求不需要处理直接放行
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 获取进入过滤器的请求
        String path = request.getServletPath();
        // 有些请求不需要进行登录检查,例如:注册、登录、主页相关的所有请求,包含Servlet与jsp
        if (path.endsWith(".user") || "/findAll.product".equals(path) || "/show.code".equals(path) || "/jsp/login.jsp".equals(path) || "/jsp/register.jsp".equals(path) || "/jsp/main.jsp".equals(path) || "/index.jsp".equals(path) || "/js/jquery-3.4.1.min.js".equals(path)) {
            // 直接放行
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 对于其他请求,均需要进行登录检查
        // 成功登录后会将用户信息保存到session中
        // 取出session中的用户信息
        User user = (User) request.getSession().getAttribute("user");
        // 如果没有取到用户信息,则说明用户未登录
        if (user == null) {
            // 此时传递错误消息,转发到登录页面
            request.setAttribute("loginMsg", "您尚未登录,请先登录!");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
            return;
        }
        // 如果取到了,则直接放行
        filterChain.doFilter(servletRequest, servletResponse);
    }
}
